<?php
include '../config.php';

function randomString($length) {
	$string = "";
 
	// genera una stringa casuale che ha lunghezza
	// uguale al multiplo di 32 successivo a $length
	for ($i = 0; $i <= ($length/32); $i++)
		$string .= md5(time() + rand(0, 99));
 
	// indice di partenza limite
	$maxStartIndex = (32 * $i) - $length;
 
	// seleziona la stringa, utilizzando come indice iniziale
	// un valore tra 0 e $max_start_point
	$randomString = substr($string, rand(0, $maxStartIndex), $length);
 
	return $randomString;
}

function hashEmailAddress($email, $salt) {
	return 'sha256$' . hash('sha256', $email . $salt);
}

function conversionUnixTimestampToDate($time) {
	$date = date_create();
	date_timestamp_set($date, $time);
	$date = date_format($date, 'Y-m-d H:i:s') . " (" . $GLOBALS['ISSUER_TIME_ZONE'] . ")\n";
	return $date;
}
	
function createFile($path, $name, $content) {
	$file = fopen($path . "/" . $name, w);
	if ($file) {
		$w = fwrite($file, $content);
		if ($w) {
			$c = fclose($file);
			if (!$c)
				return $c;
		} else {
			return $w;
		}
	} else {
		return $file;
	}	
	
	return TRUE;
}

function sendRegisteredEmail($to, $password, $admin) {
	if ($admin)
		$text = " as administrator";
	else
		$text = "";
	
	$sent = mail($to, $GLOBALS['REGISTERED_SUBJECT'], sprintf($GLOBALS['REGISTERED_HTML_CONTENT'],
			$text, $password), $GLOBALS['HTML_EMAIL_HEADERS']);
	
	return $sent;
}

function sendEarnedBadgeEmail($to, $badgeURL, $html) {
	if (!$html)
		$sent = mail($to, $GLOBALS['BADGE_EARNED_SUBJECT'], sprintf($GLOBALS['BADGE_EARNED_CONTENT'], 
				$badgeURL), $GLOBALS['EMAIL_HEADERS']);
	else
		$sent = mail($to, $GLOBALS['BADGE_EARNED_SUBJECT'], sprintf($GLOBALS['BADGE_EARNED_HTML_CONTENT'], 
				$badgeURL, $badgeURL), $GLOBALS['HTML_EMAIL_HEADERS']);
	
	return $sent;
}

function getHTTPResponseContentType($url) {
	$headers = get_headers($url, 1);
	if (isset($headers["Content-Type"]))
		return $headers["Content-Type"];
	if (isset($headers["content-type"]))
		return $headers["content-type"];
	return null;
}

function prepareString($mysqli, $string) {
	return addcslashes($mysqli->real_escape_string(trim($string)), '%_');
}

function logout() {
	// If it's desired to kill the session, also delete the session cookie.
	// Note: This will destroy the session, and not just the session data!
	if (ini_get("session.use_cookies")) {
		$params = session_get_cookie_params();
		setcookie(session_name(), '', time() - 42000,
		$params["path"], $params["domain"],
		$params["secure"], $params["httponly"]
		);
	}
	
	// Finally, destroy the session.
	session_destroy();
}

function verifyURL($url) {
	$headers = get_headers($url);
	return !(strpos($headers[0], "OK") === false);
}

function generateBadgeHTML($badgeInfo) {
	if ($badgeInfo['condivisa']) {
		$badgeInfo['issuerId'] = 0;
	}
	$string = '<span id="badge" class="' . $badgeInfo['categoriaId'] . '#' . $badgeInfo['issuerId'] . '" class="inside">';
	$string .= '<input id="opener" type="image" src="' . $badgeInfo['immagine'] . '" height="100" width="100" onclick="showInfo(\'badge' . $badgeInfo['badgeId'] . '\')"/>';
	$string .= '<div class="badgeInfo" id="badge' . $badgeInfo['badgeId'] . '" title="Badge Info">';
	$string .= '<p>Nome: ' . $badgeInfo['badgeName'] . '</p>';
	$string .= '<p>Descrizione: ' . $badgeInfo['descrizione'] . '</p>';
	if ($badgeInfo['categoriaId'] != $GLOBALS['NO_CATEGORY'])
		$string .= '<p>Categoria: ' . $badgeInfo['categoryName'] . '</p>';
	if ($badgeInfo['tags'])
		$string .= '<p>Tags: ' . $badgeInfo['tags'] . '</p>';
	if ($badgeInfo['condivisa']) {
		$string .= '<p>La badge è rilasciata da tutte le università</p>';
	} else {
		$string .= '<p>La badge è rilasciata da ' . $badgeInfo['issuerName'] . '</p>';
	}
	$string .= '<p><a href="' . $GLOBALS['ISSUER_HOST'] . '/badge_page.php?badgeId=' . $badgeInfo['badgeId'] . '">Ulteriori dettagli</a></p>';
	$string .= '</div>';
	$string .= '</span>';
	return $string;
}

function generateEarnedBadgeHTML($badgeInfo, $personal) {
	
	if (!$badgeInfo['uploaded'])
		$uploaded = 0;
	else 
		$uploaded = 1;
	
	$string = '<span id="badge" class="' . $badgeInfo['categoriaId'] . '#' . $badgeInfo['issuerId'] . '#' . $uploaded . '" class="inside">';
	$string .= '<input id="opener" type="image" src="' . $badgeInfo['immagine'] . '" height="100" width="100" onclick="showInfo(\'badge' . $badgeInfo['badgeId'] . '\')"/>';
	$string .= '<span class="badgeInfo" id="badge' . $badgeInfo['badgeId'] . '" title="Badge Info">';
	$string .= '<p>Nome: ' . $badgeInfo['badgeName'] . '</p>';
	$string .= '<p>Descrizione: ' . $badgeInfo['descrizione'] . '</p>';
	if ($badgeInfo['categoriaId'] != $GLOBALS['NO_CATEGORY'])
		$string .= '<p>Categoria: ' . $badgeInfo['categoryName'] . '</p>';
	if ($badgeInfo['tags'])
		$string .= '<p>Tags: ' . $badgeInfo['tags'] . '</p>';
	$string .= '<p>La badge è stata rilasciata da ' . $badgeInfo['issuerName'] . ' in data ' . conversionUnixTimestampToDate($badgeInfo['issuedOn']) . '</p>';
	if ($badgeInfo['expires'])
		$string .= '<p>La badge ha validità fino al giorno: ' . date('d-m-Y', $badgeInfo['expires']) . '</p>';
	if ($badgeInfo['evidence'])
		$string .= '<p><a href="' . $badgeInfo['evidence'] . '">Lavoro eseguito per conseguire la badge</a></p>';
	$string .= '<p><a href="' . $GLOBALS['ISSUER_HOST'] . '/badge_page.php?badgeId=' . $badgeInfo['badgeId'] . '">Ulteriori dettagli</a></p>';
	if ($personal && !$badgeInfo['uploaded']) {
		$singleUrl = "'" . $badgeInfo['verifyUrl'] . "'";
		$string .= '<p>' . sprintf($GLOBALS['UPLOAD_BUTTON'], "", $singleUrl, $badgeInfo['userId']) . '</p>';
	}
	$string .= '</span>';
	$string .= '</span>';
	return $string;
}
?>
